<!--
  * 云喇叭表单
-->
<template>
  <a-modal :title="props.title" :width="1000" :open="visibleFlag" @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
    <slot name="content"> </slot>
    <a-form class="smart-query-form">
      <a-row class="smart-query-form-row">
        <a-form-item label="商户名称" class="smart-query-form-item">
          <a-input style="width: 200px" v-model:value="queryForm.companyNameLeftLike" placeholder="输入商户名称" />
        </a-form-item>
        <a-form-item label="登录账号" class="smart-query-form-item">
          <a-input style="width: 200px" v-model:value="queryForm.noLeftLike" placeholder="输入登录账号" />
        </a-form-item>
        <a-form-item class="smart-query-form-item">
          <a-button type="primary" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery" class="smart-margin-left10">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-form-item>
      </a-row>
    </a-form>
    <!---------- 表格 begin ----------->
    <a-table
      size="small"
      :dataSource="tableData"
      :columns="columns"
      rowKey="id"
      bordered
      :loading="tableLoading"
      :pagination="false"
      :customRow="customRowFn"
      :row-selection="{ selectedRowKeys: selectArray.map((e) => e.id), onSelect: selectOption }"
    />
    <!---------- 表格 end ----------->
    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNo"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>
    <div v-if="selectArray.length > 0">已选择【{{ selectArray.map((item) => `${item.companyAbbrName}-${item.no}`).join(',') }}】</div>
    <template #footer>
      <a-space v-if="props.formType != 'view'">
        <a-button @click="onReset" type="link">重置</a-button>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, nextTick, computed, watch, h } from 'vue'
  import _ from 'lodash'
  import { CheckSquareOutlined, BorderOutlined } from '@ant-design/icons-vue'
  import { smartSentry } from '/@/lib/smart-sentry'
  import { merchantApi } from '/@/api/business/b-operation/merchant/merchant-api.js'
  import { merchantApi as merchantApi2 } from '/@/api/business/b-agent/merchant/merchant-api.js'
  import { merchantApi as merchantApi3 } from '/@/api/business/b-merchant/merchant/merchant-api.js'

  import { useUserStore } from '/@/store/modules/system/user'
  const USER_TYPE = useUserStore().userType // 用户类型: 1-平台;2-代理;4-商户

  const apiSource = {
    page: (data) => {
      if (USER_TYPE == '1') return merchantApi.page(data)
      if (USER_TYPE == '2') return merchantApi2.page(data)
      if (USER_TYPE == '4') return merchantApi3.page(data)
    },
  }
  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    valueKey: {
      type: String,
      default: 'id',
    },
    rowData: {
      type: Object,
      default: () => {},
    },
    title: {
      type: String,
      default: '绑定商户',
    },
  })
  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['ok', 'update:open'])
  const visibleFlag = computed({ get: () => props.open, set: (val) => emits('update:open', val) })

  const queryFormState = {
    noLeftLike: undefined,
    companyNameLeftLike: undefined,
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = reactive({ ...queryFormState })
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)

  const columns = ref([
    // {
    //   title: '序号',
    //   dataIndex: 'index',
    //   width: 60,
    //   customRender: ({ index, record }) => {
    //     return h('div', [
    //       isSelected(record)
    //         ? h(CheckSquareOutlined, {
    //             class: 'text-blue-700 p-r-2',
    //           })
    //         : h(BorderOutlined, {
    //             class: ' p-r-2',
    //           }),
    //       (queryForm.pageNo - 1) * queryForm.pageSize + index + 1,
    //     ])
    //   },
    // },
    {
      title: '序号',
      dataIndex: 'index',
      width: 60,
      customRender: ({ index }) => (queryForm.pageNo - 1) * queryForm.pageSize + index + 1,
    },
    {
      title: '登录账号',
      dataIndex: 'no',
      ellipsis: true,
    },
    {
      title: '商户名称',
      dataIndex: 'companyAbbrName',
      ellipsis: true,
    },
    {
      title: '联系人',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '联系方式',
      dataIndex: 'phone',
      ellipsis: true,
    },
  ])

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize
    Object.assign(queryForm, queryFormState)
    queryForm.pageSize = pageSize
    queryData()
  }

  // 搜索
  function onSearch() {
    queryForm.pageNo = 1
    queryData()
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true
    try {
      let queryResult = await apiSource.page(queryForm)
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }
  function onReset() {
    selectArray.value = []
  }
  // ------------------------ 显示与隐藏 ------------------------
  function onClose() {
    selectArray.value = []
    visibleFlag.value = false
  }

  // ------------------------ 获取表单数据 ------------------------

  // ------------------------ 表单 ------------------------
  const customRowFn = (record, index) => {
    return {
      onClick: (e) => {
        selectOption(record)
      },
    }
  }
  // 选择数据
  const selectArray = ref([])

  // 判断是否选中
  const isSelected = (item) => {
    if (props.multiple) {
      // 多选模式
      return selectArray.value.some((e) => e[props.valueKey] == item[props.valueKey])
    } else {
      // 单选模式
      if (selectArray.value.length === 0) return false
      return selectArray.value[0][props.valueKey] == item[props.valueKey]
    }
  }
  // 选择选项
  const selectOption = (item) => {
    if (props.multiple) {
      // 根据id判断当前点击的是否被选中
      const isS = selectArray.value.findIndex((obj) => obj[props.valueKey] == item[props.valueKey])
      if (isS >= 0) {
        selectArray.value.splice(isS, 1)
      } else {
        selectArray.value.push(item)
      }
    } else {
      selectArray.value = [item]
    }
  }
  // 点击确定，验证表单
  async function onSubmit() {
    emits('ok', selectArray.value)
  }

  watch(
    [() => props.rowData, () => props.open],
    (val) => {
      if (props.open) {
        resetQuery()
        onReset()
      }
    },
    { immediate: true },
  )
</script>
